$('document').ready(function(){
	// 回到顶部
	$("#top").click(function(){
		$('body,html').animate({scrollTop:0},1000);
		return false;
	});
	// 显示
	$(window).scroll(function(){
		if ($(window).scrollTop() > 1200){
			$("#top").fadeIn(500);
		}else{
			$("#top").fadeOut(500);
		}
	});
});


$('form[data-remote=true]').on('submit', function(e) {
  e.preventDefault(); e.stopped = true;
  var element = $(this), message = element.data('confirm');
  if (message && !confirm(message)) { return false; }
  JSAdapter.sendRequest(element, { 
    verb: element.data('method') || element.attr('method') || 'post', 
    url: element.attr('action'), 
    dataType: element.data('type') || ($.ajaxSettings && $.ajaxSettings.dataType) || 'script',
    params: element.serializeArray()
  });
});

/* Confirmation Support
 * link_to 'sign out', '/logout', :confirm => 'Log out?'
**/

$('a[data-confirm]').on('click', function(e) {
  var message = $(this).data('confirm');
  if (!confirm(message)) { e.preventDefault(); e.stopped = true; }
});

/* 
 * Link Remote Support 
 * link_to 'add item', '/create', :remote => true
**/

$('a[data-remote=true]').on('click', function(e) {
  var element = $(this); 
  if (e.stopped) return;
  e.preventDefault(); e.stopped = true;
  JSAdapter.sendRequest(element, { 
    verb: element.data('method') || 'get', 
    url: element.attr('href')
  });
});

/* 
 * Link Method Support
 * link_to 'delete item', '/destroy', :method => :delete
**/

$('a[data-method]:not([data-remote])').on('click', function(e) {
  if (e.stopped) return;
  JSAdapter.sendMethod($(this));
  e.preventDefault(); e.stopped = true;
});

/* JSAdapter */
var JSAdapter = {
  // Sends an xhr request to the specified url with given verb and params
  // JSAdapter.sendRequest(element, { verb: 'put', url : '...', params: {} });
  sendRequest: function(element, options) {
    var verb = options.verb, url = options.url, params = options.params, dataType = options.dataType;
    var event = element.trigger('ajax:before');
    if (event.stopped) return false;
    $.ajax({
      url: url,
      type: verb.toUpperCase() || 'POST',
      data: params || [],
      dataType: dataType,

      beforeSend: function(request) { element.trigger('ajax:loading',  [ request ]); },
      complete:   function(request) { element.trigger('ajax:complete', [ request ]); },
      success:    function(request) { element.trigger('ajax:success',  [ request ]); },
      error:      function(request) { element.trigger('ajax:failure',  [ request ]); }
    });
    element.trigger('ajax:after');
  },
  // Triggers a particular method verb to be triggered in a form posting to the url
  // JSAdapter.sendMethod(element);
  sendMethod: function(element) {
    var verb = element.data('method');
    var url = element.attr('href');
    var form = $('<form method="post" action="'+url+'"></form>');
    form.hide().appendTo('body');
    if (verb !== 'post') {
      var field = '<input type="hidden" name="_method" value="' + verb + '" />';
      form.append(field);
    }
    form.submit();
  }
};

// Put your application scripts here
$(function(){
  // response search query on main nav both mouse click and keyboard return key
  $('button#search-button').click(function() {
    var keyword = $.trim($('input#search-box').val());
    if (keyword != null && keyword != '') {
      $('form#cse-search-box').submit();
    }
  });
  
  $('input#search-box').keyup(function(event) {
    if (event.keyCode == 13) {
      var keyword = $.trim($('input#search-box').val());
      if (keyword != null && keyword != '') {
        $('form#cse-search-box').submit();
      }
    }
  });
});


// add function insertAtCaret which can insert something at cursor in textarea input box.
(function($){ 
  $.fn.extend({
    insertAtCaret: function(myValue) {
      var $t=$(this)[0];
      if (document.selection) {
        this.focus();
        sel = document.selection.createRange();
        sel.text = myValue;
        this.focus();
      } else if ($t.selectionStart || $t.selectionStart == '0') {
          var startPos = $t.selectionStart;
          var endPos = $t.selectionEnd;
          var scrollTop = $t.scrollTop;
          $t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length);
          this.focus();
          $t.selectionStart = startPos + myValue.length;
          $t.selectionEnd = startPos + myValue.length;
          $t.scrollTop = scrollTop;
      } else {
        this.value += myValue;
        this.focus();
      }
    }
  })
})(jQuery);

// filter illegal tag, only number, underscore, alphabet and chinese words, add #, + like C#, C++
filterTags = function(tags) {
  var newArray = new Array();
  if (tags != null && tags.length >0) {
    var re_tag = new RegExp("^(?!_)(?!.*?_$)[\+#a-zA-Z0-9_ \u4e00-\u9fa5]+$");
    var tag_list = tags.split(/\s*,\s*/);
    for(var i = 0; i< tag_list.length; i++) {
        if (re_tag.test(tag_list[i])){
          newArray.push(tag_list[i]);
      }
    }
  }
  return newArray;
};
